package com.ruoyi.web.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ParamsUtil;
import com.ruoyi.common.utils.SHA1;
import com.ruoyi.common.utils.WXCore;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.SysWxConfig;
import com.ruoyi.system.service.ISysWxConfigService;
import com.ruoyi.web.controller.common.CommonController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhimin.hu
 * @Date 2021/1/16
 */
@Api(value = "微信相关接口",tags = "微信相关接口")
@RestController
@RequestMapping("/api/wx")
public class WxApiController extends BaseApiController {
    private static final Logger logger = LoggerFactory.getLogger(CommonController.class);
    @Autowired
    private ISysWxConfigService sysWxConfigService;
    /**
     * 获取OpenId
     *
     * @param param
     * @param request
     * @return
     */
    @RequestMapping(path="/getOpenId", method =RequestMethod.POST)
    @ApiOperation("微信获取OpenId")
    @ApiImplicitParams( {
            @ApiImplicitParam(paramType = "query", name = "miniprogramNo", value = "标示ID", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "js_code", value = "微信代码", required = true, dataType = "String"),
    })
    public AjaxResult getWxOpenId(@ApiIgnore @RequestParam(required = false) Map<String, Object> param, HttpServletRequest request) {

        String msg = "";
        Object result = "";
        Map<String,Object> stringObjectMap=new HashMap<>();
        try {
            String miniprogramNo = ParamsUtil.getParamter(param, "miniprogramNo", "");
            String jsCode = ParamsUtil.getParamter(param, "js_code", "");
            SysWxConfig config= sysWxConfigService.selectSysWxConfigByMiniprogramNo(miniprogramNo);
            if (StringUtils.isBlank(jsCode) || config==null) {
                return AjaxResult.error("getWxOpenId error miniprogramNo or jsCode is null");
            }  else {
                String grant_type = "authorization_code";
                String url = "https://api.weixin.qq.com/sns/jscode2session";
                Map<String, Object> wxMap = new HashMap<>();
                wxMap.put("appid", config.getAppId());
                wxMap.put("js_code", jsCode);
                wxMap.put("secret", config.getSecretKey());
                wxMap.put("grant_type", grant_type);
                Map<String, String> header = new HashedMap();
                JSONObject r = JSONObject.parseObject(HttpUtils.sendGet(url, wxMap));
                if (r != null) {
                    System.out.println(r);
                    if (r.get("errcode") == null || r.get("errcode").toString().equals("0")) {
                        String openIdStr = r.get("openid").toString();
                        stringObjectMap.put("openId",openIdStr);
                        if(!StringUtils.isBlank(openIdStr)){
                            //登陆逻辑
                           /* XxbSocialUser socialUser=new XxbSocialUser();
                            socialUser.setOpenId(openIdStr);
                            List<XxbSocialUser> list= xxbSocialUserService.selectXxbSocialUserList(socialUser);
                            XxbUser user=new XxbUser();
                            if(list.size()>0){
                                //登陆操作
                                XxbSocialUserAuth auth=new XxbSocialUserAuth();
                                auth.setSocialUserId(list.get(0).getSocialUserId());
                                List<XxbSocialUserAuth> auths= xxbSocialUserAuthService.selectXxbSocialUserAuthList(auth);
                                if(auths.size()>0) {
                                    XxbUserLoginLog log = new XxbUserLoginLog();
                                    log.setUserId(auths.get(0).getUserId().toString());
                                    log.setSocialUserId(list.get(0).getSocialUserId().toString());
                                    log.setSource("WECHAT_OPEN");
                                    log.setPhoneModel("");
                                    log.setLoginIp(IpUtils.getIpAddr(request));
                                    log.setActionType(0);
                                    log.setIsNewUser(0);
                                    log.setDeviceNum("");
                                    log.setSearchValue("");
                                    log.setCreateBy("");
                                    log.setCreateTime(new Date());
                                    log.setRemark("");
                                    xxbUserLoginLogMapper.insertXxbUserLoginLog(log);
                                    user=xxbUserService.selectXxbUserById(auths.get(0).getUserId());
                                }
                            }else {
                                socialUser.setRemark(IpUtils.getIpAddr(request));
                                socialUser.setSource("WECHAT_OPEN");
                                socialUser.setUuid(socialUser.getOpenId());
                                user= xxbUserService.createXxbUser(socialUser);

                            }*/
                            //stringObjectMap.put("user",user);
                            return AjaxResult.success("成功", stringObjectMap);
                        }else {
                            return AjaxResult.error("openId 为空");
                        }
                    } else {
                        msg = r.get("errmsg") == null ? "" : r.get("errmsg").toString();
                        return AjaxResult.error(msg);
                    }
                } else {
                    return AjaxResult.error("请求微信失败");
                }
            }
        } catch (Exception e) {
            logger.error("api getOpenId error:url->{},请求头参数:->{},body参数：->{},异常：->{}", "getOpenId", ParamsUtil.getHeaderMap(request), ParamsUtil.getParamMap(request), e == null ? "" : e.getStackTrace());
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 获取unionId
     *
     * @param param
     * @param request
     * @return
     */
    @RequestMapping(path = "/getUnionId", method =RequestMethod.POST)
    @ApiOperation("微信获取UnionId")
    @ApiImplicitParams( {
            @ApiImplicitParam(paramType = "query", name = "miniprogramNo", value = "miniprogramNo", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "js_code", value = "js_code", required = true, dataType = "String"),
    })
    public AjaxResult getWxUnionId(@ApiIgnore @RequestParam(required = false) Map<String, Object> param, HttpServletRequest request) {

        String msg = "";
        Object result = "";
        try {
            String grant_type = "authorization_code";
            String url = "https://api.weixin.qq.com/sns/jscode2session";
            String miniprogramNo = ParamsUtil.getParamter(param, "miniprogramNo", "");
            String jsCode = ParamsUtil.getParamter(param, "js_code", "");
            SysWxConfig config= sysWxConfigService.selectSysWxConfigByMiniprogramNo(miniprogramNo);
            if (StringUtils.isBlank(jsCode) || config==null) {
                return AjaxResult.error("getWxOpenId error miniprogramNo or jsCode is null");
            } else {
                Map<String, Object> wxMap = new HashMap<>();
                wxMap.put("appId", config.getAppId());
                wxMap.put("js_code", jsCode);
                wxMap.put("secret", config.getSecretKey());
                wxMap.put("grant_type", grant_type);
                Map<String, String> header = new HashedMap();
                JSONObject r = JSONObject.parseObject(HttpUtils.sendGet(url, wxMap));

                if (r != null) {
                    if (r.get("errcode") == null || r.get("errcode").toString().equals("0")) {

                        String rawData = ParamsUtil.getParamter(param, "rawData", "");
                        String encryptedData = ParamsUtil.getParamter(param, "encryptedData", "");

                        String iv = ParamsUtil.getParamter(param, "iv", "");
                        String signatureParam = ParamsUtil.getParamter(param, "signature", "");
                        String sessionKey = r.get("session_key").toString();

                        String signature = new SHA1().getDigestOfString((rawData + sessionKey).getBytes());

                        if (!ParamsUtil.isNullOrEmpty(signatureParam)) {
                            signatureParam = signatureParam.toUpperCase();
                        }
                        if (signatureParam.equals(signature)) {
                            String decryptStr = WXCore.decrypt(config.getAppId(), encryptedData, sessionKey, iv);
                            if (!ParamsUtil.isNullOrEmpty(decryptStr)) {
                                result = JSONObject.parse(decryptStr);
                            }
                        } else {
                            return AjaxResult.error("签名校验失败");
                        }
                    } else {
                        msg = r.get("errmsg") == null ? "" : r.get("errmsg").toString();
                        return AjaxResult.error(msg);
                    }
                } else {
                    return AjaxResult.error("请求微信失败");
                }
            }
        } catch (Exception e) {
            logger.error("api getWxUnionId error:url->{},请求头参数:->{},body参数：->{},异常：->{}", "getWxUnionId", ParamsUtil.getHeaderMap(request), ParamsUtil.getParamMap(request), e == null ? "" : e.getStackTrace());
            return AjaxResult.error(e.getMessage());
        }

        return AjaxResult.success("成功", result);
    }


    /**
     * 解密微信参数
     *
     * @param param
     * @param request
     * @return
     */
    @RequestMapping(value = "/decodeWx", method = RequestMethod.POST)
    @ApiOperation("微信参数解密")
    @ApiImplicitParams( {
            @ApiImplicitParam(paramType = "query", name = "miniprogramNo", value = "miniprogramNo", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "encryptedData", value = "encryptedData", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "iv", value = "iv", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "js_code", value = "js_code", required = true, dataType = "String"),
    })
    public AjaxResult decodeWx(@ApiIgnore @RequestParam(required = false) Map<String, Object> param, HttpServletRequest request) {

        String msg = "";
        Object result = "";
        try {

            String grant_type = "authorization_code";
            String url = "https://api.weixin.qq.com/sns/jscode2session";
            String miniprogramNo = ParamsUtil.getParamter(param, "miniprogramNo", "");
            String jsCode = ParamsUtil.getParamter(param, "js_code", "");
            SysWxConfig config= sysWxConfigService.selectSysWxConfigByMiniprogramNo(miniprogramNo);
            if (StringUtils.isBlank(jsCode) || config==null) {
                return AjaxResult.error("getWxOpenId error miniprogramNo or jsCode is null");
            } else {
                Map<String, Object> wxMap = new HashMap<>();
                wxMap.put("appId", config.getAppId());
                wxMap.put("js_code", jsCode);
                wxMap.put("secret", config.getSecretKey());
                wxMap.put("grant_type", grant_type);
                Map<String, String> header = new HashedMap();
                JSONObject r = JSONObject.parseObject(HttpUtils.sendGet(url, wxMap));

                if (r != null) {
                    if (r.get("errcode") == null || r.get("errcode").toString().equals("0")) {
                        String encryptedData = ParamsUtil.getParamter(param, "encryptedData", "");
                        String iv = ParamsUtil.getParamter(param, "iv", "");
                        String sessionKey = r.get("session_key").toString();
                        String decryptStr = WXCore.decrypt(encryptedData, sessionKey, iv);
                        if (!ParamsUtil.isNullOrEmpty(decryptStr)) {
                            result = JSONObject.parse(decryptStr);
                        } else {
                            return AjaxResult.error("解密失败！");
                        }
                    } else {
                        msg = r.get("errmsg") == null ? "" : r.get("errmsg").toString();
                        return AjaxResult.error(msg);
                    }
                } else {
                    return AjaxResult.error("请求微信失败");
                }
            }
        } catch (Exception e) {
            logger.error("api decodeWx error:url->{},请求头参数:->{},body参数：->{},异常：->{}", "decodeWx", ParamsUtil.getHeaderMap(request), ParamsUtil.getParamMap(request), e == null ? "" : e.getStackTrace());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success("成功", result);
    }
}
